
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @ClassNmme:      JDBCUtils
 * @Author:         Mollen
 * @CreateDate:
 * @Description:
 *          Druid连接池工具类
 */
public class JDBCUtils {

    /**
     * 1.定义成员变量datasource
     */
    private static DataSource ds;

    /**
     * 2.获取数据源
     */
    static{
        try {
            //1.创建集合对象
            Properties pro = new Properties();
            //2.加载配置文件
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //3.获取连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  3.获取数据库连接
     */
    public static Connection getConn() throws SQLException {
        return ds.getConnection();

    }

    /**
     *  4.释放资源
     */
    public static void close(PreparedStatement st, Connection conn){
        close(null,st,conn);

    }

    public static  void close(ResultSet rs,PreparedStatement st ,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}